package com.five.controller;

import com.five.common.DataGridView;
import com.five.service.RoleService;
import com.five.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    //查询角色
    @RequestMapping("/loadAllRole")
    @PreAuthorize("hasPermission('/admin/role/toRoleManager',null)")
    public DataGridView loadAllRole(RoleVo roleVo) {
        return roleService.queryAllRole(roleVo);
    }

    //添加角色
    @RequestMapping("/addRole")
    @PreAuthorize("hasPermission('/admin/role/addRole','role:add')")
    public DataGridView addRole(RoleVo roleVo) {
        try {
            roleService.addRole(roleVo);
            return DataGridView.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return DataGridView.ADD_ERROR;
        }
    }

    //修改角色
    @RequestMapping("/updateRole")
    @PreAuthorize("hasPermission('/admin/role/updateRole','role:update')")
    public DataGridView updateRole(RoleVo roleVo) {
        try {
            roleService.updateRole(roleVo);
            return DataGridView.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return DataGridView.UPDATE_ERROR;
        }
    }

    //删除角色
    @RequestMapping("/deleteRole")
    @PreAuthorize("hasPermission('/admin/role/deleteRole','role:delete')")
    public DataGridView deleteRole(RoleVo roleVo) {
        try {
            roleService.deleteRole(roleVo.getId());
            return DataGridView.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return DataGridView.DELETE_ERROR;
        }
    }

    //加载角色管理分配菜单的json
    @RequestMapping("/initRolePermissionTreeJson")
    @PreAuthorize("hasPermission('/admin/role/saveRolePermission','role:save')")
    public DataGridView initRolePermissionTreeJson(Integer id) {
        return roleService.initRolePermissionTreeJson(id);
    }

    //保存角色和菜单的关系
    @RequestMapping("/saveRolePermission")
    @PreAuthorize("hasPermission('/admin/role/saveRolePermission','role:save')")
    public DataGridView saveRolePermission(RoleVo roleVo) {
        try {
            roleService.saveRolePermission(roleVo);
            return DataGridView.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return DataGridView.DISPATCH_ERROR;

        }
    }
}
